﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Telerik.Web.UI;

public partial class Components_Permission_RoleList : System.Web.UI.Page
{
    DatabaseHelper DB = new DatabaseHelper();
    DataTable dt = new DataTable();
    int ParentID = 44; //ID trong CSDL, bảng Function

    static int FormState = -1; //trạng thái form ban đầu
    string i_UserID;

    //Các biến lưu khóa chính, khóa phụ
    string ID = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            i_UserID = Session["UserName"].ToString();
            if (Session["Role"] == null)
                FormState = 0;
            else
                FormState = (int)Session["Role"];

            if (!IsPostBack)
            {
                SetupForm();
                switch (FormState)
                {
                    case 0:
                        {
                            break;
                        }
                    default:
                        {
                            ID = Session["Role_ID"].ToString();
                            LoadDatatoForm();
                            break;
                        }
                }
            }
            Session.Remove("Role");
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }

    protected void SetupForm()
    {
        //Load dữ liệu cho các control khi vừa load form
        Utils.LoadDataToCombo(cboParentID, "Role_cbo_ParentID", DbType.Int32, 2);

        cboParentID.SelectedIndex = 0;

        //Load dữ liệu cho các control khi StateForm = 1,2
        txtID.Text = ID;

        SetEnable();
    }

    protected void ClearForm()
    {
        cboParentID.SelectedIndex = 0;
        txtID.Text = "";
        txtRoleName.Text = "";
        txtRemark.Text = "";
        FormState = 0;
    }

    protected void SetEnable()
    {
        switch (FormState)
        {
            case 0://Thêm mới
                {
                    btnDelete.Enabled = false;
                    btnGotoList.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;

                    btnDelete.CssClass = "Enable";

                    txtID.Enabled = false;
                    break;
                }
            case 1://Sửa/Xóa
                {
                    btnDelete.Enabled = true;
                    btnGotoList.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;

                    txtID.Enabled = false;
                    break;
                }
            default://Chỉ xem
                {
                    btnDelete.Visible = false;
                    btnGotoList.Visible = false;
                    btnNew.Visible = false;
                    btnSave.Visible = false;
                    break;
                }
        }
    }

    protected void LoadDatatoForm()
    {
        try
        {
            DB.ClearParameter();

            DbParameter paramID = DB.Parameter;
            paramID.ParameterName = "ID";
            paramID.DbType = DbType.Int32;
            paramID.Value = ID;
            DB.AddParameter(paramID);

            dt = DB.ExecuteDataTable("Role_Load", CommandType.StoredProcedure, ConnectionState.CloseOnExit);

            if (dt.Rows.Count == 1)
            {
                DataRow dr = dt.Rows[0];
                cboParentID.SelectedValue = dr["ParentID"].ToString();
                txtID.Text = dr["ID"].ToString();
                txtRemark.Text = dr["Remark"].ToString();
                txtRoleName.Text = dr["RoleName"].ToString();
                string IsSystemRole = dr["IsSystemRole"].ToString();
                if (IsSystemRole == "True")
                {
                    radNo.Checked = false;
                    radYes.Checked = true;
                }
                else
                {
                    radNo.Checked = true;
                    radYes.Checked = false;
                }
            }
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }

    protected void SaveData()
    {
        DB.ClearParameter();
        try
        {
            if (txtID.Text == null || txtID.Text == "")
                FormState = 0;
            else
                FormState = 1;
            if (txtRoleName.Text == "")
            {
                txtRoleName.Focus();
                lblResult.Text = "";
                lblSuccess.Text = "";
                lblResult.Text = "Tên chức danh không rỗng";
                return;
            }
            //if (txtRemark .Text == "")
            //{
            //    lblResult.Text = "";
            //    lblSuccess.Text = "";
            //    lblResult.Text = "";
            //    txtRemark.Focus();
            //    return;
            //}
            //bỏ những ký tự đặc biệt, chống SQL Injection
            txtRoleName.Text = Utils.KillChars(txtRoleName.Text);
            txtRemark.Text = Utils.KillChars(txtRemark.Text);

            //Add param cho store
            DbParameter paramRoleName = DB.Parameter;
            paramRoleName.ParameterName = "RoleName";
            paramRoleName.DbType = DbType.String;
            paramRoleName.Value = txtRoleName.Text;
            DB.AddParameter(paramRoleName);

            DbParameter paramRemark = DB.Parameter;
            paramRemark.ParameterName = "Remark";
            paramRemark.DbType = DbType.String;
            paramRemark.Value = txtRemark.Text;
            DB.AddParameter(paramRemark);

            DbParameter paramIsSystemRole = DB.Parameter;
            paramIsSystemRole.ParameterName = "IsSystemRole";
            paramIsSystemRole.DbType = DbType.Boolean;
            paramIsSystemRole.Value = radYes.Checked == true ? 1 : 0;
            DB.AddParameter(paramIsSystemRole);

            DbParameter paramParentID = DB.Parameter;
            paramParentID.ParameterName = "ParentID";
            paramParentID.DbType = DbType.Int32;
            paramParentID.Value = cboParentID.SelectedValue;
            DB.AddParameter(paramParentID);

            DbParameter paramStatus = DB.Parameter;
            paramStatus.ParameterName = "Status";
            paramStatus.DbType = DbType.String;
            paramStatus.Value = "A";
            DB.AddParameter(paramStatus);

            DbParameter paramByUser = DB.Parameter;
            paramByUser.ParameterName = "ByUser";
            paramByUser.DbType = DbType.String;
            paramByUser.Value = i_UserID; //User đang thao tác
            DB.AddParameter(paramByUser);


            if (FormState == 0)
            {
                dt = DB.ExecuteDataTable("Role_Create", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                Session["RoleIDA"] = DB.ExecuteScalar("Role_ID", CommandType.StoredProcedure, ConnectionState.CloseOnExit).ToString();
                txtID.Text = Session["RoleIDA"].ToString();
                lblResult.Text = "";
                lblSuccess.Text = "";
                lblSuccess.Text = "Thêm mới thành công";
                btnDelete.Enabled = true;
                btnDelete.CssClass = "button";
            }
            else if (FormState == 1)
            {
                DbParameter paramID = DB.Parameter;
                paramID.ParameterName = "ID";
                paramID.DbType = DbType.Int32;
                paramID.Value = txtID.Text;
                DB.AddParameter(paramID);
                dt = DB.ExecuteDataTable("Role_Update", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                lblResult.Text = "";
                lblSuccess.Text = "";
                lblSuccess.Text = "Cập nhật thành công";
            }
        }
        catch (Exception ex)
        {
            lblSuccess.Text = "";
            lblResult.Text = "";
            lblResult.Text = "Thông báo lỗi: Lưu không thành công. Mã lỗi: Role - " + ex.Message;
        }
    }

    protected void DeleteData()
    {
        DB.ClearParameter();

        //Add param cho store
        DbParameter paramCMCode = DB.Parameter;
        paramCMCode.ParameterName = "ID";
        paramCMCode.DbType = DbType.Int32;
        paramCMCode.Value = txtID.Text;
        DB.AddParameter(paramCMCode);

        DbParameter paramByUser = DB.Parameter;
        paramByUser.ParameterName = "ByUser";
        paramByUser.DbType = DbType.String;
        paramByUser.Value = i_UserID; //User đang thao tác
        DB.AddParameter(paramByUser);

        try
        {
            dt = DB.ExecuteDataTable("Role_Delete", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            lblResult.Text = "";
            lblSuccess.Text = "";
            lblSuccess.Text = "Xóa thành công";
        }
        catch (Exception ex)
        {
            lblResult.Text = "";
            lblSuccess.Text = "";
            lblResult.Text = "Thông báo lỗi: Xóa không thành công. Mã lỗi: Role - " + ex.Message;
        }
    }

    protected Boolean CheckAllBeforeSave()
    {
        Boolean flag = true;
        if (txtRoleName.Text == "")
        {
            lblResult.Text = "[Tên quyền] không được rỗng";
            flag = false;
        }
        return flag;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            SaveData();
            btnDelete.Focus();
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            DeleteData();
            ClearForm();
            SetEnable();
            btnNew.Focus();
        }
        catch (Exception ex)
        {

            string url = "~/Default.aspx?ID=48";
            Response.Redirect(url);
            Session["ErrorMessage"] = ex.Message;

        }
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        ClearForm();
        SetEnable();
        btnGotoList.Focus();
    }

    protected void btnGotoList_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx?ID=" + ParentID);
    }
    protected void txtRoleName_TextChanged(object sender, EventArgs e)
    {
        txtRemark.Focus();
    }
    protected void cboParentID_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        txtRoleName.Focus();
    }
    protected void txtRemark_TextChanged(object sender, EventArgs e)
    {
        radYes.Focus();
    }
    protected void radYes_CheckedChanged(object sender, EventArgs e)
    {
        radNo.Focus();
    }
    protected void radNo_CheckedChanged(object sender, EventArgs e)
    {
        btnSave.Focus();
    }
}